package com.cw.framework.config;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.cw.framework.aspect.ParameterValidatorAspect;

@Configuration
public class ValidationConfig {

    @Bean
    public Validator init() {
        HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class)
            .configure();
        // 快速失败模式, 检查到第一个失败就返回
        ValidatorFactory factory = configuration.failFast(true)
            .buildValidatorFactory();
        return factory.getValidator();
    }

    @Bean
    public ParameterValidatorAspect parameterValidatorAspect(Validator validator) {
        ParameterValidatorAspect aspect = new ParameterValidatorAspect();
        aspect.setValidator(validator);
        return aspect;
    }
}